import axios from "axios";
import JSONbig from 'json-bigint'
import {notification} from 'ant-design-vue';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false });

export function initHttpClient(config, router) {
    axios.defaults.baseURL = config.baseURL();
    axios.defaults.withCredentials = true;
    axios.defaults.headers = {'Content-Type': 'application/json'};
    axios.defaults.transformResponse = [
        (data) => {
            return JSONbig.parse(data);
        }
    ];
    axios.interceptors.request.use(
        (config) => {
            NProgress.start();
            return config;
        },
        (error) => {
            return Promise.reject(error);
        }
    );
    axios.interceptors.response.use(
        (response) => {
            NProgress.done();
            if (response.data.code < 400) {
                return response;
            } else if (response.data.code === 401) {
                window.location.href = config.loginURL;
            } else if (response.data.code === 403) {
                router.replace('/403');
            } else {
                notification.error({
                    message: '错误',
                    description: response.data.message,
                });
            }
            return Promise.reject(response);
        },
        (error) => {
            NProgress.done();
            const status = error?.response?.status;
            if (status === 401) {
                window.location.href = config.loginURL;
            } else {
                notification.error({
                    message: '错误',
                    description: '请求服务器错误' + (status ? ': code=' + status : ''),
                });
                return Promise.reject(error);
            }
        }
    );
}
